﻿using System.Collections.Generic;
using System.Reflection;
using System.Xml.Linq;
using System;

namespace ProtocolBuilder.Model.Field
{
    class FieldFactory
    {
        private static Dictionary<string, ConstructorInfo> constructDict = new Dictionary<string, ConstructorInfo>();

        public static AbsField CreateField(XElement element)
        {
            string alias = element.Attribute("type").Value;
            AbsField result = CreateField(alias);
            result.XmlElement = element;

            return result;
        }

        public static AbsField CreateField(string typeAlias)
        {
            AbsField result = null;
            if (!constructDict.ContainsKey(typeAlias))
            {
                FieldType map = FieldTypeManager.GetTemplete(typeAlias);
                ConstructorInfo constructor = Assembly.LoadFile(map.AssemblyName).GetType(map.TypeFullName).GetConstructor(Type.EmptyTypes);
                constructDict.Add(typeAlias, constructor);
            }

            result = constructDict[typeAlias].Invoke(null) as AbsField;
            result.FieldType = typeAlias;

            return result;
        }
    }
}
